<?php

namespace Biz\service\bizTools;

use Doraemon\pockets\config\IniConfig;
use Doraemon\tools\Log;
use Doraemon\tools\Presto\PrestoClientV2;

class QueryWords
{

    private static $prestoClient;

    protected static function initPrestoClient()
    {
        $config = IniConfig::getConfigSelect('presto', 'brand');

        if (!self::$prestoClient instanceof PrestoClientV2) {
            self::$prestoClient = new PrestoClientV2(
                "{$config['host']}:{$config['port']}/{$config['path']}",
                "hive",
                $config["username"],
                $config["password"]
            );
        }
    }

    protected static function metabaseSqlExec(string $sql)
    {
        try {

            self::initPrestoClient();

            self::$prestoClient->Query($sql);

            self::$prestoClient->WaitQueryExec();

            $list = self::$prestoClient->GetData();

            if ($list && is_array($list)) {
                return $list;
            }

            return [];

        } catch (\Exception $e) {

            Log::error('QueryWords::metabaseSqlExec:error', ['sql' => $sql, 'err' => $e->getMessage()]);

            return [];

        }
    }

    protected static function getQuerySql($dayStart, $dayEnd, $keyWords, $limit)
    {
        $sql = "select query as \"query\" ,sum(coalesce(cnt,0)) as ct from oss.hhz.dws_search_home_query_day where day between %d and %d and query like '%%%s%%' group by query order by ct desc limit %d";

        $dayStart = intval($dayStart);
        $dayEnd = intval($dayEnd);
        $keyWords = strval($keyWords);
        $limit = intval($limit);

        $querySql = sprintf($sql, $dayStart, $dayEnd, $keyWords, $limit);

        return $querySql;
    }

    public static function query($dayStart, $dayEnd, $keyWords, $limit = 20)
    {
        $sql = self::getQuerySql($dayStart, $dayEnd, $keyWords, $limit);

        $queryRes = self::metabaseSqlExec($sql);

        $returnData = [];

        foreach ($queryRes as $key => $v){
            $returnData[$key]['query_words'] = $v[0];
            $returnData[$key]['ct'] = $v[1];
        }

        return $returnData;
    }

}